import {
    getSyctemSize
} from "../../utils/system.js"
import {
    Categories
} from "../../model/categories.js"
import {
    px2rpx
} from "../../miniprogram_npm/lin-ui/utils/util.js"

Page({

    data: {
        height: Number,
        defaultRootId: 2, //默认初始一级分类激活id
        currentRoot: null,
        currentSubs: null, //当前二级分类
        roots: [], //一级分类
        categorys: null
    },

    onLoad: function(options) {
        this._getSystem()
        this._initCategory()
    },

    //切换一级分类
    onRootChange(e) {
        let defaultRootId = e.detail.activeKey
        const currentSubs = this.data.categorys.getSubFromID(defaultRootId)
        const currentRoot = this.data.categorys.getRoot(defaultRootId)
        this.setData({
            defaultRootId,
            currentSubs,
            currentRoot
        })
    },

    // 监听二级分类item点击
    onTabItem(e) {
        const cid = e.detail.cid
        wx.navigateTo({
            url: `/pages/spu-list/spu-list?cid=${cid}`,
        })
    },

    goSearch() {
        wx.navigateTo({
            url: '/pages/search/search',
        })
    },

    /**
     * 获取当前一级分类
     * 先让本地默认查找 没有就默认第一项
     */
    getCurrentRoot(roots) {
        let locaId = this.data.defaultRootId
        let currentRoot = roots.find(item => item.id === locaId)
        if (!currentRoot) {
            return roots[0]
        }
        return currentRoot
    },

    async _initCategory() {
        const categorys = new Categories()
        await categorys.getAll()
        const roots = categorys.getRoots() // 获取一级分类
        const currentRoot = this.getCurrentRoot(roots) //获取当前一级分类
        const currentSubs = categorys.getSubFromID(currentRoot.id) //当前一级分类下的二级数据
        this.setData({
            roots,
            currentSubs,
            currentRoot,
            categorys,
            defaultRootId: currentRoot.id
        })
    },

    onShow: function() {

    },

    async _getSystem() {
        const system = await getSyctemSize()
        const height = px2rpx(system.windowHeight)
        this.setData({
            leftHeight: height - 60 - 40 - 2
        })
    }

})